import log from './logger'
import config from "./config";
import mqtt from "mqtt"

class MqttIot {
    init() {
        log.info("mqtt server: mq.wechain360.com");
        let client = mqtt.connect('mqtt://mq.wechain360.com', {
            username: "client1",
            password: "Hlsk@1234",
            protocolVersion: 5,
            clientId: config.deviceName + "-" + Date.now().toString(16),
            clean: false
        })
        client.on("connect", () => {
            log.info("mqtt connected")
        })
        client.on("error", (error: any) => {
            log.error("mqtt error", error)
        })
        client.on("reconnect", () => {
            log.info("mqtt reconnect")
        })

        // 定时上报监控数据
        setInterval(() => {
            const msg = {
                online: "online",
                device_online: "online",
            }
            client.publish(`train_node/${config.deviceName}/event/monitor`, JSON.stringify(msg), {qos: 0});
        }, 1000 * 2)
    }
}

const mqttIot = new MqttIot();
export default mqttIot;